package com.freecloud.rpc.demo1.service;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Author: maomao
 * @Date: 2021/9/1 9:56 上午
 */
public class NewIoServer {

    public static void main(String[] args) {
        //NIO重要的3个组件 Channel  / Buffer  / Selector
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //设置为非阻塞，如不增加该配置，还是阻塞状态
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(8080));
            //性能浪费，可以使用多路复用
            while (true) {
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel == null) {
                    Thread.sleep(1000);
                    System.out.println("连接未就绪");
                    continue;
                }
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                //把数据读取到缓冲区
                socketChannel.read(byteBuffer);
                System.out.println(new String(byteBuffer.array()));
                //反转
                byteBuffer.flip();
                //写出数据
                socketChannel.write(byteBuffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
